package com.wtwd.campus.thread;

import com.alibaba.fastjson.JSON;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.entity.MqTextData;
import com.wtwd.campus.entity.PushMessDataVO;
import com.wtwd.campus.utils.InjectCommandSendService;
import com.wtwd.campus.utils.InjectRedisService;
import com.wtwd.campus.wx.service.WxUtilsService;
import com.wtwd.campus.wx.utils.PushModel;
import com.wtwd.campus.wx.utils.WxUtils;
import org.apache.commons.lang.StringUtils;
import org.jeewx.api.core.req.model.message.TemplateData;
import org.jeewx.api.core.req.model.message.TemplateMessageSendResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;


public class ForkJoinPushTask extends RecursiveAction {

    private String wxPushCustomerCode;

    private WxUtilsService wxUtilsService;

    private static final Logger logger = LoggerFactory.getLogger(ForkJoinPushTask.class);
    private static final AtomicLong employeeNo = new AtomicLong();
    private static final Integer minNum = 20;
    private PushMessDataVO pushMess;
    /**
     * list为要发送的家长的openId的集合
     */
    private List<String> list;
    /**
     * listImei为要推送到设备的设备imei
     */
    private List<String> listImei;
    /**
     * 0：推送到微信  1：下发到设备
     */
    private Integer type;
    private String name;
    private static final String pushPre = "PUSH_MESS_";

    public ForkJoinPushTask(PushMessDataVO pushMessDataVO, List<String> list, Integer type) {
        if (type == 0) {
            this.list = list;
        } else if (type == 1) {
            this.listImei = list;
        }
        this.pushMess = pushMessDataVO;
        this.name = "push-thread-".concat(String.valueOf(employeeNo.getAndIncrement())).concat(":");
        this.type = type;
    }

    public ForkJoinPushTask(String wxPushCustomerCode, WxUtilsService wxUtilsService, PushMessDataVO pushMessDataVO, List<String> list, Integer type) {
        if (type == 0) {
            this.list = list;
        } else if (type == 1) {
            this.listImei = list;
        }
        this.pushMess = pushMessDataVO;
        this.name = "push-thread-".concat(String.valueOf(employeeNo.getAndIncrement())).concat(":");
        this.type = type;
        this.wxUtilsService = wxUtilsService;
        this.wxPushCustomerCode = wxPushCustomerCode;
    }


    @Override
    protected void compute() {
        if (type == 0) {
            pushToWx();
        } else if (type == 1) {
            sendToDevice();
        }
    }

    /**
     * 推送到微信
     */
    public void pushToWx() {
        try {
            if (list.size() < minNum) {
                //解析解析出不同的客户做不用的处理
                Integer customerId = 0;
                for (String e : list) {
                    String[] split = e.split(",");
                    if (split.length > 2) {
                        customerId = Integer.valueOf(split[2]);
                    }
                }
                if (customerId == 1) {//创维的
                    batchPushMessCW(list);
                } else if (customerId == 2) {
                    batchPushMessXB(list);
                } else if (wxUtilsService != null && StringUtils.isNotBlank(wxPushCustomerCode)) {
                    customerBatchPushMess(list);
                } else {
                    batchPushMess(list);
                }

            } else {
                //大于最少数则分配
                int size = list.size();
                ForkJoinPushTask aTask = new ForkJoinPushTask(pushMess, list.subList(0, size / 2), 0);
                ForkJoinPushTask bTask = new ForkJoinPushTask(pushMess, list.subList(size / 2, list.size()), 0);
                //任务拆分
                invokeAll(aTask, bTask);
            }
        } catch (Exception e) {
            //捕获异常进行处理
            logger.info((pushMess.getFlag() == 1 ? "资讯" : "通知").concat("推送发生异常，id为：").concat(pushMess.getId().toString()));
            //将异常信息存入缓存中
            String key = pushPre.concat(String.valueOf(pushMess.getTime())).concat("_").concat(String.valueOf(pushMess.getId()));
            String value = JSON.toJSONString(pushMess);
            InjectRedisService.getRedisService().setKey(key, value, 0, TimeUnit.SECONDS);
            e.printStackTrace();
        }
    }

    /**
     * 下发到设备
     */
    public void sendToDevice() {
        try {
            if (listImei.size() < minNum) {
                sendTextToDevice(listImei);
            } else {
                //大于最少数则分配
                int size = listImei.size();
                ForkJoinPushTask aTask = new ForkJoinPushTask(pushMess, listImei.subList(0, size / 2), 1);
                ForkJoinPushTask bTask = new ForkJoinPushTask(pushMess, listImei.subList(size / 2, size), 1);
                //任务拆分
                invokeAll(aTask, bTask);
            }
        } catch (Exception e) {
            //捕获异常进行处理
            e.printStackTrace();
            logger.info("通知推送到设备失败：通知id={}", pushMess.getId());
        }
    }

    /**
     * 进行推送
     */
    public void batchPushMess(List<String> list) {
        Integer flag = pushMess.getFlag();
/*        //模拟一个异常
        int i=1/0;*/
        if (flag == Constants.PUSH_NOTIFICATION) {
            //推送班级通知
            //构建模板
            TemplateMessageSendResult template = PushModel.createNotificationTemplate(pushMess.getId(), pushMess.getClassName(), pushMess.getTitle(), pushMess.getContent());
            logger.info("/模板构建内容：".concat(template.toString()));
            for (String s : list) {
                Map<String, TemplateData> data = template.getData();
                String[] split = s.split(",");
                data.put("keyword1", new TemplateData(split[1].concat("家长"), "#FF0000"));
                template.setTouser(split[0]);
                //进行推送(目前是只推送到沃特公众号用户)
                WxUtils.pushMsg(template);
            }
        } else if (flag == Constants.PUSH_INFORMATION) {
            //推送校园资讯
            Integer type = pushMess.getType();
            String typeName = "";
            switch (type) {
                case 1:
                    typeName = "教育资讯";
                    break;
                case 2:
                    typeName = "教育动态";
                    break;
                case 3:
                    typeName = "教育政策";
                    break;
                default:
                    break;
            }
            //构建模板
            TemplateMessageSendResult template = PushModel.createInformationTemplate(pushMess.getId(), typeName, pushMess.getTitle(), pushMess.getContent(), pushMess.getSchoolName());
            logger.info("/模板构建内容：".concat(template.toString()));
            for (String s : list) {
                template.setTouser(s);
                //进行推送(目前是只推送到沃特公众号用户)
                WxUtils.pushMsg(template);
            }
        }
    }

    /**
     * 进行推送
     */
    public void batchPushMessCW(List<String> list) {
        Integer flag = pushMess.getFlag();
/*        //模拟一个异常
        int i=1/0;*/
        if (flag == Constants.PUSH_NOTIFICATION) {
            //推送班级通知
            //构建模板
            TemplateMessageSendResult template = PushModel.createNotificationTemplateCW(pushMess.getId(), pushMess.getClassName(), pushMess.getTitle(), pushMess.getContent());
            logger.info("/模板构建内容：".concat(template.toString()));
            for (String s : list) {
                Map<String, TemplateData> data = template.getData();
                String[] split = s.split(",");
                data.put("keyword1", new TemplateData(split[1].concat("家长"), "#FF0000"));
                template.setTouser(split[0]);
                //进行推送(目前是只推送到沃特公众号用户)
                WxUtils.pushMsgCW(template);
            }
        } else if (flag == Constants.PUSH_INFORMATION) {
            //推送校园资讯
            Integer type = pushMess.getType();
            String typeName = "";
            switch (type) {
                case 1:
                    typeName = "教育资讯";
                    break;
                case 2:
                    typeName = "教育动态";
                    break;
                case 3:
                    typeName = "教育政策";
                    break;
                default:
                    break;
            }
            //构建模板
            TemplateMessageSendResult template = PushModel.createInformationTemplate(pushMess.getId(), typeName, pushMess.getTitle(), pushMess.getContent(), pushMess.getSchoolName());
            logger.info("/模板构建内容：".concat(template.toString()));
            for (String s : list) {
                template.setTouser(s);
                //进行推送(目前是只推送到沃特公众号用户)
                WxUtils.pushMsgCW(template);
            }
        }
    }


    public void batchPushMessXB(List<String> list) {
        Integer flag = pushMess.getFlag();
/*        //模拟一个异常
        int i=1/0;*/
        if (flag == Constants.PUSH_NOTIFICATION) {
            //推送班级通知
            //构建模板
            TemplateMessageSendResult template = PushModel.createNotificationTemplateXB(pushMess.getId(), pushMess.getClassName(), pushMess.getTitle(), pushMess.getContent());
            logger.info("/模板构建内容：".concat(template.toString()));
            for (String s : list) {
                Map<String, TemplateData> data = template.getData();
                String[] split = s.split(",");
                data.put("keyword1", new TemplateData(split[1].concat("家长"), "#FF0000"));
                template.setTouser(split[0]);
                //进行推送(推送至小湃)
                WxUtils.pushMsgXB(template);
            }
        } else if (flag == Constants.PUSH_INFORMATION) {
            //推送校园资讯
            Integer type = pushMess.getType();
            String typeName = "";
            switch (type) {
                case 1:
                    typeName = "教育资讯";
                    break;
                case 2:
                    typeName = "教育动态";
                    break;
                case 3:
                    typeName = "教育政策";
                    break;
                default:
                    break;
            }
            //构建模板
            TemplateMessageSendResult template = PushModel.createInformationTemplateXB(pushMess.getId(), typeName, pushMess.getTitle(), pushMess.getContent(), pushMess.getSchoolName());
            logger.info("/模板构建内容：".concat(template.toString()));
            for (String s : list) {
                template.setTouser(s);
                //进行推送(目前是只推送到沃特公众号用户)
                WxUtils.pushMsgXB(template);
            }
        }
    }

    public void customerBatchPushMess(List<String> list) {
        if (wxUtilsService == null || StringUtils.isBlank(wxPushCustomerCode)) {
            return;
        }
        Integer flag = pushMess.getFlag();
/*        //模拟一个异常
        int i=1/0;*/
        if (flag == Constants.PUSH_NOTIFICATION) {
            //推送班级通知
            //构建模板
            TemplateMessageSendResult template = wxUtilsService.createNotificationTemplate(wxPushCustomerCode, pushMess.getId(), pushMess.getClassName(), pushMess.getTitle(), pushMess.getContent());
            logger.info("/模板构建内容：".concat(template.toString()));
            for (String s : list) {
                Map<String, TemplateData> data = template.getData();
                String[] split = s.split(",");
                data.put("keyword1", new TemplateData(split[1].concat("家长"), "#FF0000"));
                template.setTouser(split[0]);
                //进行推送(目前是只推送到沃特公众号用户)
                wxUtilsService.pushMsg(wxPushCustomerCode, template);
            }
        } else if (flag == Constants.PUSH_INFORMATION) {
            //推送校园资讯
            Integer type = pushMess.getType();
            String typeName = "";
            switch (type) {
                case 1:
                    typeName = "教育资讯";
                    break;
                case 2:
                    typeName = "教育动态";
                    break;
                case 3:
                    typeName = "教育政策";
                    break;
                default:
                    break;
            }
            //构建模板
            TemplateMessageSendResult template = wxUtilsService.createInformationTemplate(wxPushCustomerCode, pushMess.getId(), typeName, pushMess.getTitle(), pushMess.getContent(), pushMess.getSchoolName());
            logger.info("/模板构建内容：".concat(template.toString()));
            for (String s : list) {
                template.setTouser(s);
                wxUtilsService.pushMsg(wxPushCustomerCode, template);
            }
        }
    }

    /**
     * 下发文本给设备
     *
     * @param list
     */
    public void sendTextToDevice(List<String> list) {
        MqTextData data = new MqTextData();
        data.setTitle(pushMess.getTitle());
        data.setContent(pushMess.getContent());
        list.stream().forEach(e -> {
            data.setCommandNumber(getCurTime());
            data.setImei(e);
            InjectCommandSendService.getCommandSendUtils().sendText2(data, pushMess.getUserId(), false);
        });
    }


    /**
     * 获取当前时间的时分秒（HHmmss）
     *
     * @return
     */
    public String getCurTime() {
        Date d = new Date();
        SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");
        String format = sbf.format(d);
        String[] split = format.split(":");
        String time = split[0].concat(split[1]).concat(split[2]);
        return time;
    }


}
